package com.cskaoyan.javase.annotation._4config;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 用注解提供额外信息,配置TCP编程当中的IP地址和端口号
 * @since 11:37
 * @author wuguidong@cskaoyan.onaliyun.com
 */
public class Test {
}

class TCPUtils {
    // 写两个方法分别获取注解当中的默认IP和端口号
    public static InetAddress getDefaultIP(String clazzName) throws ClassNotFoundException, UnknownHostException {
        Class<?> clazz = Class.forName(clazzName);
        if (clazz.isAnnotationPresent(TCPConfigAnno.class)) {
            // 有这个注解,配置默认IP地址
            TCPConfigAnno annotation = clazz.getAnnotation(TCPConfigAnno.class);
            String ip = annotation.ip();
            return InetAddress.getByName(ip);
        }
        // 没有这个注解,不应该调用这个方法
        return null;
    }


    public static int getDefaultPort(String clazzName) throws ClassNotFoundException, UnknownHostException {
        Class<?> clazz = Class.forName(clazzName);
        if (clazz.isAnnotationPresent(TCPConfigAnno.class)) {
            // 有这个注解,配置默认port端口号
            TCPConfigAnno annotation = clazz.getAnnotation(TCPConfigAnno.class);
            return annotation.port();
        }
        // 没有这个注解,不应该调用这个方法,返回一个负数端口号
        return -1;
    }
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TCPConfigAnno {
    String ip() default "127.0.0.1";

    int port() default 8888;
}